﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class GameEnterStateLoadBundle : GameEnterState
{
    public GameEnterStateLoadBundle(IGameEnterControl inControl)
        : base(inControl, GameState.UPDATE)
    {

    }

    private bool chekcNeedLoadBundle()
    {
        return PlayerPrefs.GetInt(ConstKey.GAME_BUNDLE, 0) == 0;
    }

    public override void Start()
    {
        control.Files = loadFileList(PathDefine.PersistentDataPath + PathDefine.FileList);
        if (null == control.Files || 0 == control.Files.Count) {
            if (Directory.Exists(PathDefine.PersistentAssetsPath)) {
                Directory.Delete(PathDefine.PersistentAssetsPath);
            }
            NextGameState = GameState.INIT;
            control.PlayNext();
        } else if (chekcNeedLoadBundle()) {
            // load bundle
            EngineFramework.Instance.StartCoroutine(LoadAssetBundle());
        } else {
            control.PlayNext();
        }

    }

    private List<string> loadFileList(string filename)
    {
        string[] files = File.ReadAllLines(filename);
        List<string> list = new List<string>(files.Length);
        for(int i=0; i<files.Length; i++) {
            if (!string.IsNullOrWhiteSpace(files[i])) {
                list.Add(files[i]);
            }
        }
        return list;
     }

    private IEnumerator LoadAssetBundle()
    {
        string streaming = PathDefine.StreamingBundlePath;
        string persistent = PathDefine.PersistentBundlePath;
        for(int i=0; i<control.Files.Count; i++) {
            string path = control.Files[i];
            string sourceFile = streaming + "/" + path;
            string destFile = persistent + "/" + path;
            using (UnityWebRequest uwq = UnityWebRequest.Get(sourceFile)) {
                yield return uwq.SendWebRequest();
                if (string.IsNullOrEmpty(uwq.error)) {
                    string parentPath = Directory.GetParent(destFile).FullName;
                    if(!Directory.Exists(parentPath)) { Directory.CreateDirectory(parentPath); }
                    FileStream fs = File.Create(destFile);
                    byte[] datas = uwq.downloadHandler.data;
                    fs.Write(datas, 0, datas.Length);
                    fs.Close();
                    uwq.Dispose();
                } else {
                    Debug.LogErrorFormat("File load error while load bundle from streaming to persistent... {0}", sourceFile);
                }
            }
        }

        PlayerPrefs.SetInt(ConstKey.GAME_BUNDLE, 1);
        control.PlayNext();
        yield return null;
    }
}
